<template>
    <div>
        <div class="search">
            <input type="text" 
            placeholder="Please input the city which you would like to search" 
            class="search-input" 
            v-model="keyword"
            >
        </div>
        <div class="search-content" v-show="keyword" ref="content">
            <ul>
                <li 
                class="search-content-item"
                v-for="(item, index) of list" 
                :key="index" 
                @click="handleClickCity(item)"
                >{{item}}</li>
                <li class="no-data" v-show="hasnoList">很抱歉，无匹配数据</li>
            </ul>
        </div>
    </div>
    
</template>
<script>
import Bscroll from 'better-scroll'
export default {
    name:"CitySearch",
    props: {
        cities: Object
    },
    data () {
        return {
            keyword: "",
            list: [],
            timer: null
        }
    },
    methods: {
        handleClickCity (city) {
            // this.$store.dispatch('clickChangeCity', city)
            this.$store.commit('changeCity',city)
            this.$router.push('/')
        }
    },
    computed: {
        hasnoList () {
            return !this.list.length
        }
    },
    mounted () {
        // 以下是Bsroll的用法
        this.scroll = new Bscroll(this.$refs.content,{click:true})
    },
    watch: {
        keyword () {
            if (this.timer) {
                clearTimeout(this.timer)
            }
            // 这里包含匿名函数的this指针作用域问题，值得研究
            const result = []
            this.timer = setTimeout(() => {
                for (let i in this.cities) {
                    this.cities[i].forEach((value)=>{ 
                        if (value.spell.indexOf(this.keyword) > -1 ||
                            value.name.indexOf(this.keyword) > -1) {
                                result.push(value.name)
                            }
                    })
                }       
            this.list = result
            // // 貌似没必要写下面这几行代码
            // if (!this.keyword) {
            //     this.list = []
            //     return
            // }
            }, 100)
        }
    }
}
</script>
<style lang="stylus" scoped>
@import "~styles/varibles.styl"
    .search
        height: .72rem
        background: $bgColor
        padding: 0 .1rem
        .search-input
            box-sizing: border-box
            height: .62rem
            line-height: .62rem
            border-radius: .06rem
            width: 100%
            color: #666
            padding: 0 .1rem
            text-align: center
    .search-content
        overflow: hidden
        position: absolute
        z-index: 1
        top: 1.58rem
        right: 0
        bottom: 0
        left: 0
        background: #eee
        .search-content-item
            line-height: .54rem
            padding-left: .2rem
        .no-data
            line-height: .54rem
            padding-left: .2rem
            
</style>